/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ni;

/**
 *
 * @author Arnaud
 */
// TCPServer.java
// A server program implementing TCP socket
import controller.ChatController;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import protocol.Port;

public class TCPServer extends Thread {

    ServerSocket listenSocket;
    Socket clientSocket;
    String filename;
    long fileSize;
    ChatController controller;

    public TCPServer(String filename, long taille, ChatController c) {
        try {

            this.filename = filename;
            this.fileSize = taille;
            controller = c;

            int serverPort = Port.receptionTCP;
            listenSocket = new ServerSocket(serverPort);

            System.out.println("server start listening... ... ...");
            
            this.start();

        } catch (IOException e) {
            System.out.println("Listen :" + e.getMessage());
        }
    }

    public void run() {

        try {
            clientSocket = listenSocket.accept();
            
            InputStream is = clientSocket.getInputStream();

            FileOutputStream fos = new FileOutputStream(filename);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            
            int count;
            byte[] buffer = new byte[8192];
            while ((count = is.read(buffer, 0, buffer.length)) > 0)
            {
                bos.write(buffer, 0, count);
            }
            
            bos.close();

            controller.controllerDisplayFileArrived(filename);

        } catch (EOFException e) {
            System.out.println("EOF:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO:" + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {/*close failed*/

            }
        }
    }
}

